define(function (require, exports, module) {
    'use strict';
    var $ = require('jquery'),
        _ = require('underscore'),
        Backbone = require('backbone'),
        notify = require('js/utils/notify'),
        user_models = require('js/apps/console/models'),
        models = require('js/apps/op/models'),
        utils = require('js/utils/tools'),
        app = Backbone.history,
        cookie = require('js/utils/cookie'),
        moment = require('moment');
    require('datetimepicker');
    require('datetimepicker');
    require('multiselect');
    require('magnific');

    var AddRechargeOrderView = Backbone.View.extend({
        tagName: "div",
        className: "panel-body pn",
        events: {
            'click #search': 'doSearch',
            'click #exportData': 'exportData',
            'click #confirmAddNewItem': 'toSaveOrCreate'
        },

        initialize: function (options) {
            this.options = options;
            this.collection = new models.AddRechargeOrderCollection();
            this.user_collection = new user_models.UserCollection();
            this.collection.bind('change remove reset', this.renderWithData, this);
        },
        render: function () {
            this.$el.html("");
            $(window).scrollTop(0);
            return this;
        },
        exportData: function (e) {
            e.preventDefault();
            if (this.collection.total == 0) {
                return;
            }
            if (this.collection.total > 1000) {
                notify.warning('警告', '数据量较大，请耐心等待');
            }
            utils.exportData(this.collection.url, this.options);
            return false;
        },
        toSaveOrCreate: function (e) {
            var attrs = utils.getAllInput('#content-form');
            attrs.start_ts = moment(attrs.start_ts).unix();
            attrs.end_ts = moment(attrs.end_ts).unix();
            attrs.content = "";
            attrs.type = attrs.recharge_type;
            attrs.sdk_version = "android_v_1_3";
            $.ajax({
                url: '/admin/pay/submit/',
                type: 'POST',
                headers: {
                    'X-AUTH-USER': cookie.getCookie('bigbang_user_id'),
                    'X-AUTH-TOKEN': cookie.getCookie('bigbang_user_token')
                },
                data: JSON.stringify(attrs)
            }).done(function (resp) {
                notify.success('提示', '新增成功！');
            }).fail(function (resp) {
                notify.error('Error', resp.statusText);
            });

            return false;
        },
        doSearch: function () {
            var options = {},
                searched = {};
            searched.id = $('#searchId').val();
            searched.user_id = parseInt($("#searchUserId").val());
            searched.created_at_lower = $("#searchCreatedAtLower").val();
            searched.created_at_upper = $('#searchCreatedAtUpper').val();
            searched.type = parseInt($('#searchType').val());
            searched.pay_type = parseInt($('#searchPayType').val());
            searched.user_type = parseInt($('#searchUserType').val());
            searched.status = parseInt($('#searchStatus').val());

            if (!isNaN(searched.user_id)) {
                options.user_id = searched.user_id;
            }
            if (searched.id) {
                options.id = searched.id;
            }
            if (searched.created_at_lower || searched.created_at_upper) {
                options.created_at = {};
                if (searched.created_at_lower) options.created_at.$gte = searched.created_at_lower;
                if (searched.created_at_upper) options.created_at.$lt = searched.created_at_upper;
            }
            if (searched.type != -1) {
                options.activity_id = searched.type ? '$!null' : '$null';
            }
            if (searched.pay_type != -1) {
                options.pay_type = searched.pay_type;
            }
            if (searched.user_type != -1) {
                options.user_type = searched.user_type;
            }
            options.status = searched.status;
            options.is_fresh = 0;
            utils.saveSearched('op/add_recharge_order', searched);
            app.navigate(utils.composeQueryString('#op/add_recharge_order/', options), {
                trigger: true
            });
        },
        renderWithData: function () {
            this.$el.html(this.template({
                items: this.collection.toJSON(),
                searched: utils.getSearched('op/add_recharge_order'),
                overview: this.collection.overview,
            }));
            var that = this;


            $('#addNewItem').magnificPopup({
                items: {
                    src: '#addNewItemPanel',
                    type: 'inline'
                },
                midClick: true,
                closeOnBgClick: false,
                callbacks: {
                    beforeOpen: function () {
                        that.uuid = utils.generateUUID();
                        $('#cancelAddNewItem').off('click').click(function () {
                            $.magnificPopup.close();
                        });

                        $('#confirmAddNewItem').off('click').click(function () {
                            // that.confirmAddNewItem();
                            that.toSaveOrCreate();
                            $.magnificPopup.close();

                        });
                    }
                }
            });

            utils.renderTable('main-list', {
                $orderby: that.options.$orderby || '-created_at',
                sortCallback: function (field) {
                    that.options.$orderby = field;
                    that.options.$page = 1;
                    var newUrl = utils.composeQueryString('#op/add_recharge_order/', that.options);
                    app.navigate(newUrl, {
                        trigger: true
                    });
                }
            });
            $('[data-type=date]').datetimepicker({
                defaultDate: false,
                format: 'YYYY-MM-DD'
            });


            $('.modify-item').magnificPopup({
                items: {
                    src: '#editWithdrawPanel',
                    type: 'inline'
                },
                midClick: true,
                closeOnBgClick: false,
                callbacks: {
                    beforeOpen: function () {
                        var data_id = $(this.st.el).closest('tr').data('id'),
                            choosen = that.collection.get(data_id);
                        $('#order_id').text(choosen.get('id'));
                        if(2 == choosen.get('status')){
                            $('#pay_status').text('已支付');
                        }else{
                            $('#pay_status').text('未支付');
                        }
                        $('#created_at').text(choosen.get('created_at'));
                        $('#updated_at').text(choosen.get('updated_at'));
                        $('#user_id').text(choosen.get('user_id'));
                        $('#user_type').text(USER_TYPE[choosen.get('user_type')]);
                        $('#recharge_type').text(PAY_TYPE[choosen.get('pay_type')]);
                        $('#recharge_price').text(choosen.get('price'));
                        $('#recharge_ent').text(choosen.get('activity_name'));

                        $('#submitClose').off('click').click(function() {
                            $.magnificPopup.close();
                        });

                    },
                }
            });

            utils.getPaginator(that.options, this.collection.total, '#op/add_recharge_order/');
            return this;
        },
        load: function () {
            this.collection.fetch({
                reset: true,
                data: this.options,
                error: function (c, r, o) {
                    notify.notifyResp(r);
                    $('#content').append('<h4 class="text-muted">无数据</h4>');
                },
            });
        }
    });
    exports.List = Backbone.View.extend({
        el: "#content_wrapper",
        template: "op/AddRechargeOrder.html",
        initialize: function (options) {
            this.options = options;
        },
        render: function () {
            if(this.options.is_fresh === undefined) this.options.is_fresh = 1;
            this.options.status = 0;
            this.options.created_by = 2;
            var view = new AddRechargeOrderView(this.options);
            view.template = this.template;
            this.$el.empty();
            this.$el.append(view.render().el);
            view.load();
            return this;
        }
    });
});
